package cn.edu.niit.servlet;

import cn.edu.niit.javabean.Book;
import cn.edu.niit.service.BookService;
import com.alibaba.fastjson.JSON;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @program: Library
 * @ClassName: SearchBooksServlet
 * @description: Test
 * @author: Cai
 * @date: 2021/4/12 16:06
 **/
@WebServlet(name = "SearchBooksServlet", urlPatterns = "/book/search")
public class SearchBooksServlet extends HttpServlet {

    private BookService bookService = new BookService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String paramJson= IOUtils.toString(
                req.getInputStream(),"UTF-8");
        HashMap<String, Object> parseObject= JSON.parseObject(
                paramJson, HashMap.class);



        //1.取参(当前的页码，每页的数量，搜索的数量)
        String param = (String) parseObject.get("search");
        int pageNum = (int) parseObject.get("pageNum");
        int pageSize = (int) parseObject.get("pageSize");
        List<Book> books=new ArrayList<>();
        int count=0;
        //2.
        if (param != null) {
            //带参数查询


        } else {
            //无参数查询
            books = bookService.searchAllBooks(pageNum, pageSize);
        }

        count=bookService.countNum();

        //3.将结果放入session
        req.getSession().setAttribute("books",books);
//        req.getSession().setAttribute("count",count);
        resp.getWriter().print(count);

    }
}
